<template>
	<a-card :bordered="false">
		<a-form ref="searchFormRef" name="advanced_search" :model="searchFormState" class="ant-advanced-search-form">
			<a-row :gutter="24">
				<a-col :span="6">
					<a-form-item label="账户号" name="account">
						<a-input v-model:value="searchFormState.account" placeholder="请输入账户号" />
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="账户名称" name="accountName">
						<a-input v-model:value="searchFormState.accountName" placeholder="请输入账户名称" />
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-button type="primary" @click="tableRef.refresh()">查询</a-button>
					<a-button style="margin: 0 8px" @click="reset">重置</a-button>
				</a-col>
			</a-row>
		</a-form>
		<s-table
			ref="tableRef"
			:columns="columns"
			:data="loadData"
			:alert="options.alert.show"
			bordered
			:row-key="(record) => record.id"
			:tool-config="toolConfig"
			:row-selection="options.rowSelection"
		>
			<template #operator class="table-operator">
				<a-space>
					<a-button type="primary" @click="formRef.onOpen()" v-if="hasPerm('imsBankAccountAdd')">
						<template #icon><plus-outlined /></template>
						新增
					</a-button>

					<a-button @click="batchModal.onOpen()">
						<template #icon><import-outlined /></template>
						<span>{{ $t('common.imports') }}</span>
					</a-button>
					<a-button @click="exportBatchUser">
						<template #icon><export-outlined /></template>
						{{ $t('user.batchExportButton') }}
					</a-button>

					<xn-batch-delete
						v-if="hasPerm('imsBankAccountBatchDelete')"
						:selectedRowKeys="selectedRowKeys"
						@batchDelete="deleteBatchImsBankAccount"
					/>
				</a-space>
			</template>
			<template #bodyCell="{ column, record }">
				<template v-if="column.dataIndex === 'status'">
					{{ $TOOL.dictTypeData('COMMON_STATUS', record.status) }}
				</template>
				<template v-if="column.dataIndex === 'action'">
					<a-space>
						<a @click="formRef.onOpen(record)" v-if="hasPerm('imsBankAccountEdit')">编辑</a>
						<a-divider type="vertical" v-if="hasPerm(['imsBankAccountEdit', 'imsBankAccountDelete'], 'and')" />
						<a-popconfirm title="确定要删除吗？" @confirm="deleteImsBankAccount(record)">
							<a-button type="link" danger size="small" v-if="hasPerm('imsBankAccountDelete')">删除</a-button>
						</a-popconfirm>
					</a-space>
				</template>
			</template>
		</s-table>
	</a-card>
	<Form ref="formRef" @successful="tableRef.refresh()" />

	<xn-form-container title="导入导出" :width="700" :visible="batchModal.visible" :destroy-on-close="true" @close="batchModal.onClose">
		<span>导入数据格式严格按照系统模板进行数据录入，请点击
			<a-button type="primary" size="small" @click="batchModal.downloadImportUserTemplate">下载模板</a-button>
		</span>
		<a-divider dashed />
		<div>
			<a-spin :spinning="batchModal.impUploadLoading">
				<a-upload-dragger :show-upload-list="false" :custom-request="batchModal.customRequestLocal" :accept="batchModal.uploadAccept">
					<p class="ant-upload-drag-icon">
						<inbox-outlined></inbox-outlined>
					</p>
					<p class="ant-upload-text">单击或拖动文件到此区域进行上传</p>
					<p class="ant-upload-hint">仅支持xls、xlsx格式文件</p>
				</a-upload-dragger>
			</a-spin>
		</div>
		<a-alert v-if="batchModal.impAlertStatus" type="info" :show-icon="false" banner closable @close="batchModal.onImpClose" class="mt-3">
			<template #description>
				<p>导入总数：{{ batchModal.impResultData.totalCount }} 条</p>
				<p>导入成功：{{ batchModal.impResultData.successCount }} 条</p>
				<div v-if="batchModal.impResultData.errorCount > 0">
					<p><span class="xn-color-red">失败条数：</span>{{ batchModal.impResultData.errorCount }} 条</p>
					<a-table :dataSource="batchModal.impResultErrorDataSource" :columns="batchModal.impErrorColumns" size="small" />
				</div>
			</template>
		</a-alert>
	</xn-form-container>

</template>

<script setup name="basics">
	import tool from '@/utils/tool'
	import { cloneDeep } from 'lodash-es'
	import Form from './form.vue'
	import imsBankAccountApi from '@/api/ims/imsBankAccountApi'
	import {message} from "ant-design-vue";
	import userApi from "@/api/sys/userApi";

	import downloadUtil from '@/utils/downloadUtil'



	// 批量导入
	const batchModal = ref({
		visible: false,
		impUploadLoading: false,
		impAlertStatus: false,
		impResultData: false,
		impResultErrorDataSource: false,


		 onOpen: () => {
			 batchModal.value.visible = true
		},
		// 关闭抽屉
		onClose: () => {
			batchModal.value.visible = false
			// 关闭导入的提示
			batchModal.value.onImpClose()
			tableRef.value.refresh()
		},
		// 下载用户导入模板
		downloadImportUserTemplate :() => {
			imsBankAccountApi.downloadImportTemplate().then((res) => {
				downloadUtil.resultDownload(res)
			})
		},
		// 指定能选择的文件类型
		uploadAccept : String(
			[
				{
					extension: '.xls',
					mimeType: 'application/vnd.ms-excel'
				},
				{
					extension: '.xlsx',
					mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
				}
			].map((item) => {
				return item.mimeType
			})
		),
		impErrorColumns :[
			{
				title: '索引',
				dataIndex: 'index',
				width: '80px'
			},
			{
				title: '原因',
				dataIndex: 'msg'
			}
		],
		impAccept : [
			{
				extension: '.xls',
				mimeType: 'application/vnd.ms-excel'
			},
			{
				extension: '.xlsx',
				mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
			}
		],
		// 关闭导入提示
		onImpClose : () => {
			batchModal.value.impAlertStatus = false
		},
		customRequestLocal : (data) => {
			batchModal.value.impUploadLoading = true
			const fileData = new FormData()
			// 校验上传文件扩展名和文件类型是否为.xls、.xlsx
			const extension = '.'.concat(data.file.name.split('.').slice(-1).toString().toLowerCase())
			const mimeType = data.file.type
			// 提取允许的扩展名
			const extensionArr = batchModal.value.impAccept.map((item) => item.extension)
			// 提取允许的MIMEType
			const mimeTypeArr = batchModal.value.impAccept.map((item) => item.mimeType)
			if (!extensionArr.includes(extension) || !mimeTypeArr.includes(mimeType)) {
				message.warning('上传文件类型仅支持xls、xlsx格式文件！')
				batchModal.value.impUploadLoading = false
				return false
			}
			fileData.append('file', data.file)
			return imsBankAccountApi
				.import(fileData)
				.then((res) => {
					batchModal.value.impAlertStatus = true
					batchModal.value.impResultData = res
					batchModal.value.impResultErrorDataSource = res.errorDetail

					tableRef.value.refresh()
				})
				.finally(() => {
					batchModal.value.impUploadLoading = false
				})
		}
	})
	// 批量导出
	const exportBatchUser = () => {
		imsBankAccountApi.export().then((res) => {
			downloadUtil.resultDownload(res)
			tableRef.value.clearSelected()
		})
	}


	const searchFormState = ref({})
	const searchFormRef = ref()
	const tableRef = ref()
	const formRef = ref()
	const toolConfig = { refresh: true, height: true, columnSetting: true, striped: false }
	const columns = [
		{
			title: '账户号',
			dataIndex: 'account'
		},
		{
			title: '账户名称',
			dataIndex: 'accountName'
		},
		{
			title: '行号',
			dataIndex: 'bankNo'
		},
		{
			title: '账户管理员',
			dataIndex: 'accountAdmin'
		},
		{
			title: '状态',
			dataIndex: 'status'
		},
		{
			title: '备注',
			dataIndex: 'remark'
		},
	]
	// 操作栏通过权限判断是否显示
	if (hasPerm(['imsBankAccountEdit', 'imsBankAccountDelete'])) {
		columns.push({
			title: '操作',
			dataIndex: 'action',
			align: 'center',
			width: 150
		})
	}
	const selectedRowKeys = ref([])
	// 列表选择配置
	const options = {
		// columns数字类型字段加入 needTotal: true 可以勾选自动算账
		alert: {
			show: true,
			clear: () => {
				selectedRowKeys.value = ref([])
			}
		},
		rowSelection: {
			onChange: (selectedRowKey, selectedRows) => {
				selectedRowKeys.value = selectedRowKey
			}
		}
	}
	const loadData = (parameter) => {
		const searchFormParam = cloneDeep(searchFormState.value)
		return imsBankAccountApi.imsBankAccountPage(Object.assign(parameter, searchFormParam)).then((data) => {
			return data
		})
	}
	// 重置
	const reset = () => {
		searchFormRef.value.resetFields()
		tableRef.value.refresh(true)
	}
	// 删除
	const deleteImsBankAccount = (record) => {
		let params = [
			{
				id: record.id
			}
		]
		imsBankAccountApi.imsBankAccountDelete(params).then(() => {
			tableRef.value.refresh(true)
		})
	}
	// 批量删除
	const deleteBatchImsBankAccount = (params) => {
		imsBankAccountApi.imsBankAccountDelete(params).then(() => {
			tableRef.value.clearRefreshSelected()
		})
	}
</script>
